package com.tsfyun.scm.service.impl.third;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.tsfyun.common.base.enums.MessageNodeEnum;
import com.tsfyun.common.base.enums.shortmsg.ShortMessagePlatformEnum;
import com.tsfyun.common.base.support.OperationEnum;
import com.tsfyun.scm.base.support.AliyunMsgOperation;
import com.tsfyun.scm.config.properties.AliyunProperties;
import com.tsfyun.scm.entity.third.LogSms;
import com.tsfyun.scm.service.third.ILogSmsService;
import com.tsfyun.scm.service.third.AbstractMessageService;
import com.tsfyun.scm.service.third.IMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

@RefreshScope
@Service(value = "aliyunMessage")
@Slf4j
public class AlyMessageServiceImpl extends AbstractMessageService implements IMessageService   {

    @Resource
    private AliyunProperties aliyunProperties;

    @Autowired
    private ILogSmsService logSmsService;

    @Transactional(rollbackFor = Exception.class)
    public void sendVerificationCode(LogSms logSms) {
        String message = "";
        if(Objects.equals(isSend,Boolean.TRUE)) {
            OperationEnum aliYunMessageTemplate = AliyunMsgOperation.getInstance().getMessageTemplate().get(MessageNodeEnum.of(logSms.getNode()));
            if(Objects.isNull(aliYunMessageTemplate)) {
                log.warn("阿里云短信平台【{}】未找到短信节点【{}】的配置，不发送短信平台",aliYunMessageTemplate.getName(),MessageNodeEnum.of(logSms.getNode()).getName());
                return;
            }
            message = send(aliYunMessageTemplate.getCode(),logSms.getPhoneNo(),String.format("{\"code\":\"%s\"}",logSms.getCode()));
        } else {
            message = "阿里云短信发送未开启";
        }
        logSms.setBackMessage(message);
        logSmsService.updateById(logSms);
    }

    /**
     * 发送短信对接短信平台
     * @param templateCode      短信模板编码
     * @param phoneNo          手机号码
     * @param templateParam    模板参数  字符串参数
     * @return
     */
    public String send(String templateCode,String phoneNo,String templateParam){
        try {
            DefaultProfile profile = DefaultProfile.getProfile("default", aliyunProperties.getAccessKeyId(), aliyunProperties.getAccessKeySecret());
            IAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            //request.setProtocol(ProtocolType.HTTPS);
            request.setMethod(MethodType.POST);
            request.setDomain(aliyunProperties.getDomain());
            request.setAction("SendSms");
            request.setVersion("2017-05-25");
            request.putQueryParameter("TemplateCode", templateCode);
            request.putQueryParameter("SignName", aliyunProperties.getSignName());
            request.putQueryParameter("PhoneNumbers", phoneNo);
            request.putQueryParameter("TemplateParam", templateParam);
            CommonResponse response = client.getCommonResponse(request);
            //错误编码说明
            //https://help.aliyun.com/document_detail/101346.html?spm=a2c4g.11186623.2.14.633f56e08G6YwG
           return response.getData();
        } catch (Exception e) {
            log.error("短信发送失败：",e);
        }
        return "发送失败";
    }

    @Override
    public ShortMessagePlatformEnum getPlatform() {
        return ShortMessagePlatformEnum.ALIYUN;
    }

}
